<?php

if_get('/elements', function ()
{/*{{{*/
    list(
        $inputs['name'], $inputs['key'], $inputs['type'], $inputs['event_id']
    ) = input_list(
        'name', 'key', 'type', 'event_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $elements = dao('element')->find_all_by_column($inputs);

    return [
        'count' => count($elements),
        'elements' => array_build($elements, function ($id, $element) {
            return [
                null,
                [
                    'id' => $element->id,
                    'name' => $element->name,
                    'key' => $element->key,
                    'type' => $element->get_type_description(),
                    'event_display' => $element->event->display_for_elements_event(),
                    'create_time' => $element->create_time,
                    'update_time' => $element->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/elements/add', function ()
{/*{{{*/
    $name = input('name');
    otherwise_error_code('ELEMENT_REQUIRE_NAME', $name);
    $key = input('key');
    otherwise_error_code('ELEMENT_REQUIRE_KEY', $key);
    $type = input('type');
    otherwise_error_code('ELEMENT_REQUIRE_TYPE', $type);

    $another_element = dao('element')->find_by_name_and_key_and_type($name, $key, $type);
    otherwise_error_code('ELEMENT_DUPLICATED', $another_element->is_null(), [':element_id' => $another_element->id]);

    $element = element::create(
        input_entity('event', null, 'event_id'),
        $name,
        $key,
        $type
    );

    return [
        'id' => $element->id,
    ];
});/*}}}*/

//todo::detail

if_post('/elements/update/*', function ($element_id)
{/*{{{*/
    $name = input('name');
    $key = input('key');
    $type = input('type');

    $element = dao('element')->find($element_id);
    otherwise_error_code('ELEMENT_NOT_FOUND', $element->is_not_null());

    $another_element = dao('element')->find_by_name_and_key_and_type($name, $key, $type);
    otherwise_error_code('ELEMENT_DUPLICATED', $another_element->is_null() || $another_element->id === $element->id, [':element_id' => $another_element->id]);

    $element->event = input_entity('event', null, 'event_id');
    $element->name = $name;
    $element->key = $key;
    $element->type = $type;

    return true;
});/*}}}*/

if_post('/elements/delete/*', function ($element_id)
{/*{{{*/
    $element = dao('element')->find($element_id);
    otherwise_error_code('ELEMENT_NOT_FOUND', $element->is_not_null());

    $element->delete();

    return true;
});/*}}}*/
